/**
 * Copyright (C) 2010 OpenWeb Technology Inc.
 */

package photosalvage.logging;

import java.lang.reflect.Method;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;

import photosalvage.entity.User;
import photosalvage.rs.BaseResource;

/**
 * @author shumpei
 *
 */
public class UserTrackingLogInterceptor implements MethodInterceptor {
	
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object thisObj = invocation.getThis();
		if (thisObj instanceof BaseResource) {
			BaseResource rs = (BaseResource) thisObj;
			try {
				Object result = invocation.proceed();
				if (result instanceof Response) {
					log(invocation, (Response) result, rs);
				}
				return result;
			} catch (Throwable t) {
				if (t instanceof WebApplicationException) {
					Response resp = ((WebApplicationException) t).getResponse();
					log(invocation, resp, rs);
				}
				throw t;
			}
		} else {
			return invocation.proceed();
		}
	}
	private void log(MethodInvocation invocation, Response resp, BaseResource rs) {
		String userId = "#NONE#";
		String email = "#NONE#";
		Method method = invocation.getMethod();
		String className = method.getDeclaringClass().getName();
		String methodName = method.getName();
		String args = StringUtils.join(invocation.getArguments(), ",");
		args = args.replace("\"", "\"\"");
		
		User user = rs.getCurrentUser();
		if (user != null) {
			userId = String.valueOf(user.getId());
			email = user.getEmail();
		}
		Object[] logEntries = new Object[] {
				userId, email, className, methodName, args, resp.getStatus()
		};
		String log = "\"" + StringUtils.join(logEntries, "\",\"") + "\"";
		Loggers.USER_TRACKING_LOGGER.info(log);
	}
}
